/**
 * 
 */
package core;

import java.net.URL;
import java.net.URLConnection;
import java.util.Observable;
import java.util.Observer;

import model.FileDownloadProgress;
import model.LinkParsingData;

/**
 * @author Ken
 *
 */
public class DownloadManager extends Observable implements Observer {
	private DownloadManager() { }
	public static DownloadManager GetInstance() {
		if (instance == null) instance = new DownloadManager();
		return instance;
	}
	public void GetLinkInfo(String link) {
		try {
			URL url = new URL(link);			
			String protocol = url.getProtocol();			
			String fileName = url.getFile().substring(url.getFile().lastIndexOf("/") + 1);
			int port = url.getPort();
			int defaultPort = url.getDefaultPort();			
			URLConnection conn = url.openConnection();			
			int size = conn.getContentLength();
			LinkParsingData data = new LinkParsingData(link, protocol, fileName, port, defaultPort, size);
			setChanged();
			notifyObservers(data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void Download(String link) {
		DownloadComponent component = new DownloadComponent();
		component.addObserver(this);		
		component.StartDownload(link);		
	}
	@Override
	public void update(Observable o, Object data) {		
		FileDownloadProgress progress = (FileDownloadProgress) data;
		System.out.println("Downloaded: " + progress.percent);
	}
	static DownloadManager instance;
	public static final int NUM_THREAD = 10;
}
